package com.hyzx.qbasic.admin.common.util;

import com.hyzx.qbasic.admin.model.annotation.SysLog;
import com.hyzx.qbasic.common.util.JsonUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 黄江华 on 2018/5/18
 * 请求过滤器工具类
 */

public class RequestFilterUtils {

    public static String getMethodInfo(Method method,String methodName) {
        ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
        SysLog sysLogAnnotation = method.getAnnotation(SysLog.class);
        String methodInfo;
        if (apiOperation != null)
            methodInfo = apiOperation.value();
        else if (sysLogAnnotation != null)
            methodInfo = sysLogAnnotation.value();
        else
            methodInfo = methodName;

        return methodInfo;
    }

    public static boolean isRestfulApi(Method method) {
        Class<?> declaringClass = method.getDeclaringClass();

        RestController restControllerAnnotation = declaringClass.getAnnotation(RestController.class);
        if (restControllerAnnotation != null) {
            return true;
        }

        Controller controllerAnnotation = declaringClass.getAnnotation(Controller.class);
        ResponseBody responseBodyAnnotation = method.getAnnotation(ResponseBody.class);
        if (controllerAnnotation != null && responseBodyAnnotation != null) {
            return true;
        }

        return false;
    }

    public static String getRequestParams(Object[] args) {
        if (args == null || args.length == 0)
            return StringUtils.EMPTY;

        List<Object> paramList = new ArrayList<>(args.length);
        for (Object param : args) {
            if (param instanceof Model)
                continue;

            if (param instanceof HttpServletRequest)
                continue;

            if (param instanceof HttpServletResponse)
                continue;

            if (param instanceof BindingResult)
                continue;

            if (param instanceof MultipartFile)
                continue;

            if (param instanceof MultipartFile[])
                continue;

            paramList.add(param);
        }

        if (paramList.size() == 0)
            return StringUtils.EMPTY;

        String reqParams = JsonUtils.beanToJson(paramList);
        return reqParams;
    }
}
